import {ref, getCurrentInstance, h, reactive, markRaw, shallowRef} from 'vue'
import {ajax} from 'framework'


function parseMeta(components, meta, dataForm) {

    const searchControls = []
    const tableItems = []
    for (let f of meta.fieldMetas) {
        //search
        if (f.searchCondition) {
            searchControls.push({
                control: components.Input,
                field: f.field,
                props: {
                    type: 'text',
                    placeholder: f.title
                }
            })
        }
        //list
        if (f.visibleInList) {
            tableItems.push(h(components.TableItem, {
                title: f.title,
                prop: f.field,
                format: (s) => s + 'aa'
            }))
        }
        //form
        if (f.visibleInForm) {
            dataForm.items.push({
                title: f.title,
                prop: f.field,
                control: components.Input,
                props: {
                    type: 'text',
                    placeholder: f.title
                }
            })
        }

    }

    const TableGrid = (props, context) => {
        return h(components.Table, props, [...tableItems, h(components.TableItem, {title: '操作', width: 120}, (c) =>
            h(components.LinkButtons, {}, [
                h(components.Button, {
                    onClick() {
                        context.emit('edit', c.data)
                    }
                }, ["编辑"]),
                h(components.Button, {
                    onClick() {
                        context.emit('delete', c.data)
                    }
                }, ["删除"])
            ])
        )])
    }
    dataForm.open = function (v) {
        dataForm.opened = true
    }


    return {
        TableGrid,
        searchControls
    }
}

export function useTableMeta(id) {
    const meta = ref({})
    const metaLoaded = ref(false)
    const components = getCurrentInstance().appContext.components

    let proxy = {}

    const searchControls = ref([])
    const dataForm = reactive({
        opened: false,
        loading:false,
        data: {},
        rules: {},
        items: []
    })
    ajax.get('model/' + id + '/meta').then(r => {
        //r.data
        meta.value = r.data
        proxy = parseMeta(components, r.data, dataForm)
        searchControls.value = proxy.searchControls
        metaLoaded.value = true
    })
    return {
        metaLoaded,
        meta,
        TableGrid: (props, context) => {
            return proxy.TableGrid(props, context)
        },
        searchControls,
        dataForm
    };
}
